<template>
  <a-modal
    :dialogStyle="{top:'50px'}"
    title="授权角色"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >

    <a-card :bordered="false">
      <div>
        <a-form :form="form">
          <a-table
            :scroll="{y:640}"
            size="small"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :dataSource="loadData"
            :pagination="false"
            :loading="loading"
            :rowKey="(record) => record.id"
          >
            <template slot="action" slot-scope="text,record,index">
              <a-form-item style="margin: 0;padding: 0">
                <a-switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  :disabled="disableSwitch(record)"
                  v-decorator="[`check${index}`,{valuePropName: 'checked',initialValue:record.isMainRole} ]"
                  @click="(e) =>onChangeRadio(e,record,index)"
                />
              </a-form-item>
            </template>
          </a-table>
        </a-form>
      </div>

    </a-card>

  </a-modal>
</template>

<script>
import {getRolePage} from '@/api/modular/system/roleManage'
import {sysUserGrantRole, sysUserOwnRole} from '@/api/modular/system/userManage'

const columns = [
    { title: '角色名称',align:'center', dataIndex: 'name' },
    { title: '唯一编码',align:'center', dataIndex: 'code' },
    { title: '是否为主角色',align:'center', scopedSlots: { customRender: 'action' }}
  ]

  export default {
    name: 'UserRoleIndex',

    data () {
      return {
        form: this.$form.createForm(this),
        columns,
        loadData: [],
        selectedRowKeys: [], // Check here to configure the default column
        loading: true,
        visible: false,
        confirmLoading: false,
        recordEntity: []
      }
    },
    computed: {
      hasSelected () {
        return this.selectedRowKeys.length > 0
      }
    },
    methods: {
      // 初始化方法
      userRole (record) {
        this.recordEntity = record
        this.visible = true
        // 获取全部列表,无需分页
        getRolePage().then((res) => {
          // 加载已有数据
          this.loadData = res.data.rows
          this.sysUserOwnRole()
        })
      },

      /**
       * 获取用户已有角色
       */
      sysUserOwnRole () {
        this.loading = true
        sysUserOwnRole({ id: this.recordEntity.id }).then((res) => {
          // 选中多选框
          // this.selectedRowKeys = res.data
          //由于接口返回数据从普通数组改为对象数组，故这里需要修改
          for(const item of res.data){
            this.selectedRowKeys.push(item.roleId)
            for(const row of this.loadData ){
              if(item.roleId==row.id){
                row.isMainRole = item.isMainRole === 0 ? false: true
                break
              }
            }
          }
          this.loading = false
        })
      },

      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      /**
       * 是否已勾选
       */
      disableSwitch(record){
        if(this.selectedRowKeys.includes(record.id)) {
          return false
        }
        return true
      },
      /**
       * 开关选择
       */
      onChangeRadio(value,record,index){
        if(value){
          this.loadData.forEach((item,idx)=>{
            this.form.setFieldsValue({
              [`check${idx}`]:false
            })
            this.form.setFieldsValue({
              [`check${index}`]:true
            })
            this.loadData[index].isMainRole = true
          })
        }else{
          this.form.setFieldsValue({
            [`check${index}`]:false
          })
          this.loadData[index].isMainRole = false
        }

      },
      handleSubmit () {
        // eslint-disable-next-line no-unused-expressions
        this.confirmLoading = false
        this.visible = false
        const result = this.loadData.filter(item=>item.isMainRole)[0]
        const isMainRoleId = result ? result.id : undefined
        sysUserGrantRole({ id: this.recordEntity.id, grantRoleIdList: this.selectedRowKeys,isMainRoleId }).then((res) => {
           if (res.success) {
             this.$message.success('授权成功')
             this.confirmLoading = false
             this.$emit('ok', this.recordEntity)
             this.handleCancel()
           } else {
             this.$message.error('授权失败：' + res.message)
            }}).finally((res) => {
             this.confirmLoading = false
            })
      },
      handleCancel () {
        this.recordEntity = []
        this.selectedRowKeys = []
        this.visible = false
      }
    }
  }
</script>

<style scoped>
  /deep/ .ant-card-body{
    padding: 12px;
  }
 /deep/ .ant-modal-body{
   padding: 0;
 }
 /deep/ ant-table-row-selected{
    background: red !important;
  }
 /deep/ .ant-form-item-control{
   line-height: 0;
 }

</style>
